<template>
  <div>
    <!--      面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
<!--        展开列-->
        <el-table-column type="expand">
<!--          作用域插槽，通过slot-scope="scope"在插槽中进行传值-->
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0?'bdtop':'', 'vcenter']" v-for="(item1, i1) in scope.row.children"
                    :key="item1.id">
<!--              渲染一级权限-->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              通过嵌套for循环渲染二级和三级权限-->
              <el-col :span="19">
                <el-row :class="[i2 === 0?'':'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable
                            @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" :class="[i3 === 0?'':'bdtop']" v-for="(item3, i3) in item2.children"
                            :key="item3.id" closable
                            @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
<!--        索引列-->
        <el-table-column label="ID" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!--            作用域插槽-->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

<!--    添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!--    内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--    底部区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </el-dialog>

<!--    编辑角色对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!--    内容主体区域-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--    底部区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRole(editForm.roleId)">确 定</el-button>
  </span>
    </el-dialog>

<!--    分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed">
      <!-- 树形组件
          show-checkbox:显示复选框
          node-key:设置选中节点对应的值
          default-expand-all:是否默认展开所有节点
          :default-checked-keys 设置默认选中项的数组
          ref:设置引用 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id"
               default-expand-all ref="treeRef" :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Roles',
    data() {
      return {
        rolesList: [],
        //添加角色对话框显示与隐藏的标志
        addDialogVisible: false,
        addForm: {
          roleName: '',
          roleDesc: ''
        },
        addFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 3, max: 9, message: '长度应在 3 到 9 个字符', trigger: 'blur' }
          ]
        },

        //编辑角色对话框显示与隐藏的标志
        editDialogVisible: false,
        //查询到的被编辑的角色信息需要存储在editForm
        editForm: {},
        //编辑角色的验证规则
        editFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 3, max: 9, message: '长度应在 3 到 9 个字符', trigger: 'blur' }
          ]
        },

        //所有权限的数据
        rightsList: [],
        //树形控件的属性绑定对象
        treeProps: {
          //通过label设置树形节点文本展示authName
          label: 'authName',
          //设置通过children属性展示子节点信息
          children: 'children'
        },
        //默认选中的权限节点的Id值数组
        defKeys: [],
        //当前即将被分配权限的角色Id
        roleId: '',
        //分配权限对话框显示与隐藏的标志
        setRightDialogVisible: false
      }
    },
    created() {
      this.getRolesList();
    },
    methods: {
      //获取角色列表
      async getRolesList() {
        const {data: res} = await this.$http.get('roles');
        if (res.meta.status !== 200) return this.$message.error('角色列表获取失败');
        // console.log(res.data);
        this.rolesList = res.data;
      },

      //添加角色
      addRole() {
      //  预验证添加角色的信息
        this.$refs.addFormRef.validate(async vaild => {
          if (!vaild) return;
          const {data: res} = await this.$http.post('roles', this.addForm);
          if (res.meta.status !== 201) return this.$message.error('角色创建失败');
          this.addDialogVisible = false;
          this.getRolesList();
        })
      },
      //监听关闭添加角色对话框的事件
      addDialogClosed() {
        //在关闭时对话框时，重置对话框中的内容
        this.$refs.addFormRef.resetFields();
      },

      //显示编辑角色信息的对话框,并将需要修改的角色信息渲染在对话框中
      async showEditDialog(id) {
        this.editDialogVisible = true;
        const {data: res} = await this.$http.get(`roles/${id}`);
        if (res.meta.status !== 200) return this.$message.error('获取角色信息失败');
        this.editForm = res.data;
      },

      //监听修改角色对话框的关闭事件,关闭时重置editForm的内容
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      //编辑角色信息
      editRole(id) {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          // console.log(this.editForm);
          const {data: res} = await this.$http.put(`roles/${id}`, this.editForm);
          // console.log(res);
          if (res.meta.status !== 200) return this.$message.error('更新失败');
          this.$message.success('更新成功');
          this.editDialogVisible = false;
          this.getRolesList();
        })
      },

      // 根据id删除角色
      async removeRole(id) {
        const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        //如果确认删除，则confirmRes的返回值为 confirm
        //如果取消删除，则confirmRes的返回值为 cancel
        if (confirmRes === 'cancel') return this.$message.info('已取消删除');
        const {data: res} = await this.$http.delete(`roles/${id}`);
        if (res.meta.status !== 200) return this.$message.error('删除失败');
        this.getRolesList();
        this.$message.success('删除成功');
      },

      //删除角色指定权限
      async removeRightById(role, rightId) {
        const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        //  通过catch 捕获错误
        }).catch(err => err);
        //如果确认删除，则confirmRes的返回值为 confirm
        //如果取消删除，则confirmRes的返回值为 cancel
        if (confirmRes === 'cancel') return this.$message.info('已取消删除');
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
        if (res.meta.status !== 200) return this.$message.error('权限删除失败');
        // this.getRolesList();
        this.$message.success('权限删除成功');
        role.children = res.data;
      },

      //显示分配权限对话框
      async showSetRightDialog(role) {
        this.roleId = role.id;
        const {data: res} = await this.$http.get('rights/tree');
        this.setRightDialogVisible = true;
        if (res.meta.status !== 200) return this.$message.error('权限列表获取失败');
        // console.log(res.data);
        this.rightsList = res.data;
        this.getLeafKeys(role, this.defKeys);
        this.setRightDialogVisible = true;
      },

      //通过递归的形式，获取角色下所有的三级权限的id，并保存到 defKeys 数组中
      getLeafKeys(node, arr) {
         if (!node.children) {
           return arr.push(node.id);
         }
         node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      //监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.defKeys = [];
      },

      //点击为角色分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ];
        const idStr = keys.join(',')
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr});
        if (res.meta.status !== 200) return this.$message.error('分配权限失败');
        this.$message.success('分配权限成功');
        this.getRolesList();
        this.setRightDialogVisible = false;
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-table {
    margin-top: 15px;
  }
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
